<template>
  <page-header title="山海商城" background="#F7F0E6" :needHome="needHome"
    style="position: fixed;width: 100%;top: 0;z-index: 100;"></page-header>
  <view class="background"></view>
  <view class="page-index" :style="{paddingTop:`${70+securityHeight*2}rpx`}">
    <!-- 搜索框 -->
    <view class="search-box">
      <view class="search" @tap="toSrearch">
        <view class="icon">
          <image src="/static/images/search.png" />
        </view>
        <view class="text">
          搜索您想购买的商品或者店铺
        </view>
      </view>
    </view>

    <!-- banner -->
    <view class="banner">
      <view class="bg">
        <!-- <image src="/static/images/bannerBg.png" /> -->
      </view>
      <swiper class="img" indicator-dots="true" indicator-color="rgba(255,252,255, .3)"
        indicator-active-color="rgba(255,252,255, .6)" autoplay="true" circular="true">
        <swiper-item v-for="item in indexImgs" :key="item.imgId" class="item">
          <image :src="item.imgUrl" mode="aspectFill" />
        </swiper-item>
      </swiper>
    </view>

    <view class="down-select">
      <view class="type">
        <view class="name" @tap="popup.show=true;popup.type=0">{{Data.popup.name[0]}}
          <uni-icons type="down" size="10"></uni-icons>
        </view>
        <view class="name" @tap="popup.show=true;popup.type=1">{{Data.popup.name[1]}}
          <uni-icons type="down" size="10"></uni-icons>
        </view>
        <view class="name" style="margin:0 0 0 auto" @tap="selected()">
          <uni-icons type="circle" size="20" color="#DA9974" v-if="!Data.selectedExchange"></uni-icons>
          <uni-icons type="circle-filled" color="#DA9974" size="20" v-else></uni-icons>
          我能兑换
        </view>
      </view>
      <view class="type-popup" v-if="popup.show">
        <view class="item-box" v-if="popup.type==0">
          <view :class="{item:true,itemActive:'全部类型'==Data.popup.name[0]}" @tap.stop="changeSearchType(item)">全部类型
          </view>
          <view :class="{item:true,itemActive:item.name==Data.popup.name[0]}" @tap.stop="changeSearchType(item)"
            v-for="item in Data.categoryList" :key="item.categoryId">{{item.name}}</view>
        </view>
        <view class="item-box" v-else>
          <view :class="{item:true,itemActive:Data.popup.name[1]=='不限制积分'}" @tap.stop="changeSearchPointRange(-1,-1)">
            不限制积分</view>
          <view :class="{item:true,itemActive:Data.popup.name[1]=='0-1000积分'}"
            @tap.stop="changeSearchPointRange(0,1000)">0-1000积分</view>
          <view :class="{item:true,itemActive:Data.popup.name[1]=='1000-2000积分'}"
            @tap.stop="changeSearchPointRange(1000,2000)">1000-2000积分</view>
          <view :class="{item:true,itemActive:Data.popup.name[1]=='2000-3000积分'}"
            @tap.stop="changeSearchPointRange(2000,3000)">2000-3000积分</view>
          <view :class="{item:true,itemActive:Data.popup.name[1]=='3000积分以上'}"
            @tap.stop="changeSearchPointRange(3000,-1)">3000积分以上</view>
        </view>
      </view>
    </view>
    <view class="prods">
     <shop-item class="item" :shopItem="item" v-for="item in categoryProdList" :key="item.spuId"
        @tap="toProdDetail(item.spuId)"></shop-item>
    </view>

    <empty-img v-if="categoryProdList.length===0">
      <template #text>
        暂无符合商品~
      </template>
    </empty-img>

    <view v-if="isLoadAll && categoryProdList.length>0" class="nomore">
      没有更多了，看看别的吧
    </view>
  </view>
</template>

<script setup>
  import {
    onShareTimeline,
    onShareAppMessage
  } from '@dcloudio/uni-app';
  import {
    onShow
  } from '@dcloudio/uni-app';
  const wxs = number()
  const Data = reactive({
    popup: {
      show: false,
      type: 0,
      name: ['全部类型', '不限制积分']
    },
    // 返回参数
    noticeData: {
      list: [], // 返回的列表
      total: 0, // 一共多少条数据
      pages: 0 // 一共多少页
    },
    indexImgs: [], // 轮播图
    categoryList: [], // 分类列表
    selectedIndex: 0, // 选中的分类项(默认为第一个分类)
    selectedCategoryId: '',
    // 分类商品列表的请求参数
    searchListQuery: {
      pageSize: 10,
      pageNum: 1,
      primaryCategoryId: '',
      sort: 1, // 新品 1:新品
      maxPointPrice: '',
      minPointPrice: '',
    },
    // 分类商品列表返回的参数
    searchListData: {
      list: [],
      total: 0, // 总数
      pages: 0 // 总页数
    },
    categoryProdList: [], // 分类的商品列表
    origincategoryProdList: [], // 未过滤的商品列表
    isLoadAll: false, // 是否加载全部
    selectedExchange: false, // 是否选中我能兑换
    // 分类滚动栏横向滚动距离
    categoryScrollLeft: 0,
    // 分类滚动的总宽度
    contentScrollW: 0,
    isWechat: false, // 是否为微信环境
    needHome: false // 返回按键是否跳转首页，如果页面来自分享，返回按键跳转首页
  })
  const {
    indexImgs,
    popup,
    selectedExchange,
    categoryList,
    selectedIndex,
    categoryProdList,
    origincategoryProdList,
    isLoadAll,
    categoryScrollLeft,
    needHome
  } = toRefs(Data)

  onLoad(() => {
    queryDataGroup()
  })

  onShow(() => {
    let pages = getCurrentPages()
    if (pages.length === 1) {
      Data.needHome = true
    }
    uni.removeStorageSync('cloudUserInfo')
  })
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom(() => {
    if (Data.searchListQuery.pageNum < Data.searchListData.pages) {
      Data.searchListQuery.pageNum = Data.searchListQuery.pageNum + 1
      getSearchList()
    } else {
      Data.isLoadAll = true
    }
  })
  /**
   * 跳转商品详情
   */
  const toProdDetail = (spuId) => {
    if (spuId) {
      uni.navigateTo({
        url: '/pages/shop-detail/shop-detail?spuId=' + spuId
      })
    }
  }

  /**
   * 查询页面数据方法合集
   */
  const queryDataGroup = () => {
    getIndexImgs()
    getPlatformCategoryList()
  }

  /**
   * 轮播图
   */
  const getIndexImgs = () => {
    uni.showLoading()
    http.request({
      url: '/mall4cloud_point/ua/listIndexImg?type=1',
      method: 'GET'
    }).then((res) => {
      uni.hideLoading()
      Data.indexImgs = res
    })
  }

  /**
   * 获取商品列表
   */
  const getSearchList = () => {
    uni.showLoading()
    Data.isLoadAll = false
    const filteredParams = {};
    for (const key in Data.searchListQuery) {
      if (Data.searchListQuery[key] !== '') {
        filteredParams[key] = Data.searchListQuery[key];
      }
    }
    http.request({
      url: '/mall4cloud_search/ua/search/simple_page',
      method: 'GET',
      data: filteredParams
    }).then(res => {
      Data.searchListData = res
      let list = []
      if (Data.searchListQuery.pageNum === 1) {
        list = res.list[0].spus
      } else {
        list = Data.categoryProdList
        list = list.concat(res.list[0].spus)
      }
      if (Data.searchListQuery.pageNum === Data.searchListData.pages) {
        Data.isLoadAll = true
      }
      Data.categoryProdList = list
      Data.origincategoryProdList = list
      filterData()
      uni.hideLoading()
    })
  }

  /**
   * 获取平台分类
   */
  const getPlatformCategoryList = () => {
    uni.showLoading()
    http.request({
      url: '/mall4cloud_product/ua/category/category_list',
      method: 'GET',
      data: {
        shopId: 0,
        parentId: 0
      }
    }).then(res => {
      Data.categoryList = res
      getSearchList()
      uni.hideLoading()
    })
  }

  /**
   * 切换分类
   */
  const switchCategory = (e) => {
    const index = parseInt(e.currentTarget.dataset.index)
    Data.selectedCategoryId = parseInt(e.currentTarget.dataset.categoryid)
    if (Data.selectedIndex === index) {
      return
    }
    Data.selectedIndex = index
    Data.searchListQuery.pageNum = 1
    // scorll-view 实现居中显示的滚动位置(偏移值): 当前点击子元素距离左边栏的距离 - scroll-view 宽度的一半  + 当前点击子元素一半的宽度 - 父盒子边距(如有)
    Data.categoryScrollLeft = Data.categoryList[index].left - Data.contentScrollW / 2 + Data.categoryList[index]
      .width / 2 - 15
    getSearchList()
  }

  const scroll = (e) => {
    setTimeout(() => {
      Data.categoryScrollLeft = e.target.scrollLeft
    })
  }

  // 跳转搜索页
  const toSrearch = () => {
    uni.navigateTo({
      url: '/pages/search-page/search-page'
    })
  }

  // 跳转新品推荐
  const toNewProds = () => {
    uni.navigateTo({
      url: '/pages/new-prods/new-prods'
    })
  }

  const notOpen = (title) => {
    uni.showModal({
      title: '提示',
      content: `${title}暂未开源`,
      showCancel: false
    })
  }

  /**
   * 修改搜索类型
   */
  const changeSearchType = (item) => {
    Data.popup.name[0] = item ? item.name : '全部类型'
    Data.searchListQuery.primaryCategoryId = item ? item.categoryId : ''
    Data.popup.show = false
    getSearchList()
  }

  /**
   * 修改积分范围
   */
  const changeSearchPointRange = (min, max) => {
    Data.popup.name[1] = min == 3000 ? '3000积分以上' : min >= 0 ? `${min}-${max}积分` : '不限制积分'
    Data.searchListQuery.maxPointPrice = max >= 0 ? max : ''
    Data.searchListQuery.minPointPrice = min >= 0 ? min : ''
    Data.popup.show = false
    getSearchList()
  }

  /**
   * 选择'我能兑换'
   */
  const filterData = () => {
    if (Data.selectedExchange) {
      uni.getStorage({
        key: 'cloudUserInfo',
        success(res) {
          const info = res.data
          Data.categoryProdList = Data.categoryProdList.filter(item => {
            return Number(item.pointPrice) <= Number(info.point)
          })
        },
        fail() {
          http.request({
            url: '/mall4cloud_user/a/user/ma/user_detail_info',
            method: 'GET'
          }).then(res => {
            uni.setStorageSync("cloudUserInfo", res)
            Data.categoryProdList = Data.categoryProdList.filter(item => {
              return Number(item.pointPrice) <= Number(res.point)
            })
          })
        }
      })
    }
  }

  const selected = () => {
    if (!uni.getStorageSync('cloudToken')) {
      uni.showModal({
        title: '提示',
        content: '该功能登录后开放哦',
        confirmText: '去登录',
        success: modalRes => {
          if (modalRes.confirm) {
            // 跳转登录页面
            uni.navigateTo({
              url: '/pages/login/login'
            })
          }
        }
      })
    } else {
      Data.selectedExchange = !Data.selectedExchange
      if (Data.selectedExchange) {
        filterData()
      } else {
        Data.categoryProdList = Data.origincategoryProdList
      }
    }
  }

  /**
   * 获取安全距离
   */
  const securityHeight = ref(0)
  const getSecurityHeight = () => {
    let app = uni.getSystemInfoSync()
    securityHeight.value = app.statusBarHeight + 3
  }
  getSecurityHeight()
</script>

<style>
  page {
    background-color: #FFFCF5;
  }
</style>

<style lang="scss" scoped>
  @use "mall-index";
</style>
